layui.define(['layer'], function(exports) {
	var $ = layui.jquery,
		layer = layui.layer;

	var step = {
		options: {},
		// 渲染步骤条
		render: function(options) {
			options.speed = options.speed || 'fast';

			this.options = options;

			if (options.width) $(options.elem).css('width', /^\d+$/.test(options.width) ? options.width + 'px' : options.width);

			// 渲染主体表单
			this.buildBody(options);

			// 创建步骤条
			this.buildHeader(options);

			return this;
		},

		buildHeader: function(options) {
			var stepHeader = options.width ? '<div class="step-header"><ul>' : '<div class="step-header"><ul>';
			for (var i = 0; i < options.stepItems.length; i++) {
				stepHeader += '<li class="' + (i === 0 ? 'active' : '') + '">' +
					'<div class="step-title">' + options.stepItems[i].title + '</div>' +
					(options.stepItems[i].desc ? '<div class="step-desc">' + options.stepItems[i].desc + '</div>' : '') +
					'</li>';
			}
			stepHeader += '</ul></div>';
			$(options.elem).prepend(stepHeader);
		},

		buildBody: function(options) {
			$(options.elem).html('<div class="step-body">' + $(options.elem).html() + '</div>');
		},

		// 下一步
		next: function() {
			this.index(this.index() + 1);
		},

		// 上一步
		prev: function() {
			this.index(this.index() - 1);
		},

		// 定位
		index: function() {
			var header_this = $('.step-header > ul > li.active:last', this.options.elem);

			if (!arguments || arguments.length === 0)
				return header_this.index();

			var l = $('.step-header > ul > li', this.options.elem).length,
				i = this.index(),
				n = arguments[0];

			if (n >= l) n = 0;
			else if (n < 0) n = l - 1;

			if (i === n) return false;

			$('.step-body', this.options.elem).animate({ left: -100 * n + '%' }, this.options.speed, function() {
				$('.step-header > ul > li:nth-child(-n + ' + (n + 1) + ')').addClass('active');
				$('.step-header > ul > li:nth-child(n + ' + (n + 2) + ')').removeClass('active');
			});
		}
	};

	layui.link(layui.cache.base + 'step/step.css');

	exports('step', step);
});